#!/usr/bin/python


from HTMLParser import HTMLParser


class BaseHTMLProcessor(HTMLParser):
    """class for processing base html file"""
    def __init__(self):
        """init function of BaseHTMLProcessor"""
        HTMLParser.__init__(self)
        self.counter = 0

    def reset(self):
        """extend (called by SGMLParser.__init__)"""
        self.pieces = []
        HTMLParser.reset(self)

    def handle_starttag(self, tag, attrs):
        """called for each start tag"""
        if self.counter > 0:
            strattrs = "".join([' %s="%s"' % (key, value) for \
                                key, value in attrs])
            self.pieces.append("<%(tag)s%(strattrs)s>" % locals())

    def handle_endtag(self, tag):
        """called for each end tag"""
        if self.counter > 0:
            self.pieces.append("</%(tag)s>" % locals())
            
    def handle_startendtag(self, tag, attrs):
        """called for startend tag <some />"""
        if self.counter > 0:
            strattrs = "".join([' %s="%s"' % (key, value) for \
                                key, value in attrs])
            self.pieces.append("<%(tag)s%(strattrs)s />" % locals())



    def handle_charref(self, ref):
        """called for each character reference,
        e.g. for "&#160" ref will be 160"""
        return HTMLParser.handle_charref(self, ref) and \
                HTMLParser.handle_charref(self, ref) or ""

    def handle_entityref(self, ref):
        """called for each entity reference, e.g. for &copy"""
        return HTMLParser.handle_entityref(self, ref) and \
                HTMLParser.handle_entityref(self, ref) or ""

    def handle_data(self, text):
        """called for each block of plain text"""
        if self.counter > 0:
            self.pieces.append(text)

    def handle_comment(self, text):
        """called for text comment"""
        if self.counter > 0:
            self.pieces.append("<!--%(text)s-->" % locals())

    def handle_pi(self, text):
        """called for each processing instruction"""
        if self.counter > 0:
            self.pieces.append("<?%(text)s>" % locals())

    def handle_decl(self, text):
        """called for the DOCTYPE"""
        if self.counter > 0:
            self.pieces.append("<!%(text)s>" % locals())

    def output(self):
        """Return processed HTML as a single string"""
        return "".join(self.pieces)
    
    def resetPiece(self):
        """Reset piece"""
        self.pieces = []
